using System;
using System.IO;
using System.Collections.Generic;

namespace MathSharp.Script
{
	public class IncludeCommand: BaseCommand
	{
		Script includedScript;
		
		public IncludeCommand(Script script): base(script)
		{
		}
		
		public override void Parse (IList<string> scriptText)
		{
			base.Parse(scriptText);
			if (scriptText.Count != 1)
				throw new ParseException(script.FileName, baseScriptLine, 0, 0x0,
				                         "Ошибка синтаксиса команды include: команда не может быть описанна на {0} строках",
				                         scriptText.Count);
			string[] flElements = scriptText[0].Split(new char[] {' ', '\t'}, 2, StringSplitOptions.RemoveEmptyEntries);
			FileName = flElements[1];
			if (!File.Exists(FileName))
				throw new ParseException(script.FileName, baseScriptLine, 0, 0x0,
				                         "Не найден файл подключаемого скрипта {0}",FileName);
			includedScript = new Script(FileName);
		}
		
		public string FileName {
			get;
			protected set;
		}
		
		public override string Name {
			get {
				return "Include script: {0}".format(FileName);
			}
		}

		public override void PrepareExecute ()
		{
			base.PrepareExecute();
			if (includedScript == null)
				throw new PrepareExecuteException(script.FileName, baseScriptLine, 0, 0x0,
				                                  "Подключаемый скрипт небыл загружен");
			includedScript.PrepareExecute();
		}
		
		public override Value Execute ()
		{
			base.Execute();
			return script.Execute();
		}
	}
}

